// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database();
const _ = db.command;
const myOrbit = db.collection("myOrbit");
const myTravel = db.collection("myTravel");

// 云函数入口函数
exports.main = async (event, context) => {
  console.log("send message begin");
  const now = new Date(new Date().getTime() + 28800000);
  const today = now.getFullYear() + '/' + (now.getMonth() + 1) + '/' + now.getDate();
  var countTravel = await myTravel.where({
    send:true
  }).count();
  var total = countTravel.total;
  var batchTimes = Math.ceil(total / 100);
  var travel2send = [];
  var page =0;
  for (var i=0;i<batchTimes;i++){
    var t = await myTravel.where({
      send:true
    }).skip(page).get();
    travel2send = travel2send.concat(t.data);
    page+=100;
  }
  //只能一次订阅有点坑人啊
  for (var i =0 ;i<travel2send.length;i++){
    try{
      await cloud.openapi.subscribeMessage.send({
        touser:travel2send[i]._openid,
        templateId:"bx5cmwANfNaUckblXPSsK4QUuQEL1JrPULCpwJSvZyg",
        data:{
          time2:{
            value:today,
          },
          thing1:{
            value:"您于"+travel2send[i].date+"乘坐的"+travel2send[i].number+"您的出行存在感染风险，请到小程序查看",
          }
        },
        page:"pages/my/travel/travel"
      })
    }catch(err){
      console.log(err);
    }
  }

  //重置send
  await myTravel.where({
    send:true,
  }).update({
    data:{
      send:false
    }
  })


  var countOrbit = await myOrbit.where({
    send:true
  }).count();
  var total = countOrbit.total;
  var batchTimes = Math.ceil(total / 100);
  var orbit2send = [];
  var page =0;
  for (var i=0;i<batchTimes;i++){
    var t = await myOrbit.where({
      send:true
    }).skip(page).get();
    orbit2send = orbit2send.concat(t.data);
    page+=100;
  }
  for (var i =0 ;i<orbit2send.length;i++){
    try{
      await cloud.openapi.subscribeMessage.send({
        touser:orbit2send[i]._openid,
        templateId:"bx5cmwANfNaUckblXPSsK4QUuQEL1JrPULCpwJSvZyg",
        data:{
          time2:{
            value:today,
          },
          thing1:{
            value:"您的活动存在感染风险，请到小程序查看",
          }
        },
        page:"pages/my/orbit/orbit"
      })
    }catch(err){
      console.log(err);
    }
  }

  await myOrbit.where({
    send:true,
  }).update({
    data:{
      send:false
    }
  })


  return {
   success:true
  }
}